package cn.itcast.service.impl;

import cn.itcast.dao.ProvinceDao;
import cn.itcast.domain.Province;
import cn.itcast.service.ProvinceService;
import cn.itcast.utils.JedisUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.util.StringUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import redis.clients.jedis.Jedis;

import java.util.List;

public class ProvinceServiceImpl implements ProvinceService {
    @Override
    public List<Province> findAll() throws Exception {
        Jedis jedis = JedisUtils.getJedis();
        String provinces = jedis.get("provinces");

        if (StringUtil.isEmpty(provinces)){
            System.out.println("没有从缓存中查到数据");

            SqlSession sqlSession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("MyBatisConfig.xml")).openSession();
            ProvinceDao provinceDao = sqlSession.getMapper(ProvinceDao.class);
            List<Province> list = provinceDao.findAll();
            sqlSession.close();

            String json = new ObjectMapper().writeValueAsString(list);
            jedis.set("provinces",json);

            return list;
        }else {
            System.out.println("从缓存中查到数据,是"+provinces);

            List list = new ObjectMapper().readValue(provinces, List.class);
            return list;
        }
    }
}
